package net.avcompris.binding.impl;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;

import com.avcompris.common.annotation.Nullable;

final class XPathFunctionComposite implements XPathFunction {

	public XPathFunctionComposite(final Iterable<XPathFunction> functions) {

		this.functions = nonNullArgument(functions, "functions");
	}

	private final Iterable<XPathFunction> functions;

	@Override
	public Object evaluate(@Nullable final Object[] args) {

		final int paramCount = (args == null) ? 0 : args.length;

		for (final XPathFunction function : functions) {

			if (!function.matchesArity(paramCount)) {
				continue;
			}

			return function.evaluate(args);
		}

		return null;
	}

	@Override
	public boolean matchesArity(final int arity) {

		for (final XPathFunction function : functions) {

			if (function.matchesArity(arity)) {
				return true;
			}
		}

		return false;
	}
}
